// components/list/list.js
const computedBehavior = require('miniprogram-computed').behavior
Component({
  behaviors: [computedBehavior],
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    // 购物车的数据
    cartList: []
  },
  pageLifetimes: {
    show() {
      let cart = wx.getStorageSync('cart', cart)
      this.setData({
        cartList: cart
      })
      console.log(this.data.cartList);
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 获取复选框的状态
    checkedChange(e) {
      // 获取传递过来的下标
      let index = e.currentTarget.dataset.index
      // 取反
      this.data.cartList[index].checked = !this.data.cartList[index].checked
      this.setData({
        cartList: this.data.cartList
      })
      wx.setStorageSync('cart', this.data.cartList)
    },
    // 点击全选实现复选
    allChecked() {
      let val = this.data.cartList.every(item => {
        return item.checked
      })
      console.log(val);
      this.data.cartList.forEach(item => {
        item.checked = !val
      })
      this.setData({
        cartList: this.data.cartList
      })
    },
    // 点击数量拿到变化后的数量
    countClick(e) {
      let index = e.currentTarget.dataset.index
      this.data.cartList[index].count = e.detail
      this.setData({
        cartList: this.data.cartList
      })
    },
    // 点击删除
    del(e) {
      console.log(e);
      let index = e.currentTarget.dataset.index
      let list = this.data.cartList
      this.data.cartList.splice(index, 1)
      this.setData({
        cartList: this.data.cartList
      })
      wx.showToast({
        title: '删除成功',
      })
      wx.setStorageSync('cart', this.data.cartList)
    },
    // 提交表单
    handleSubmit() {
      // 过滤出来选中的商品
      let order = this.data.cartList.filter(item => item.checked)
      wx.setStorageSync('order', order)
      if (order.length) {
        wx.navigateTo({
          url: '/pages/order/order',
        })
      } else {
        wx.showToast({
          title: '请选择商品',
          icon: 'error'
        })
      }
    }
  },
  // 小程序计算属性是没有this的
  computed: {
    // 计算总价
    totalPrice(data) {
      return data.cartList.reduce((total, item) => {
        if (item.checked) {
          return total += item.count * item.minPrice
        } else {
          return total
        }
      }, 0)

    },
    // 点击复选实现全选
    checkedAll(data) {
      // 购物车里有数据的时候
      if (data.cartList.length) {
        // 遍历  当都是true的时候返回true
        return data.cartList.every(item => {
          return item.checked
        })
      } else {
        return false
      }
    }
  }
})